table_2_age_new <- function( group,
                             data = data_probs_new,
                             one_way = F) {
  
  res<- table_2_func(name = group,
                     data_probs = data[DMG_age_quintiles == group] , 
                     type_reweight_oneway = one_way,
                     parm_bins = 0.2,num_of_bins = 5
  )
  
  return(res[[1]])
}

do_all_age_groups<- function(type,
                             data = data_probs_new,
                             one_way=F,
                             age_groups) {
  
  res_type <- lapply(age_groups,
                     table_2_age_new,
                     data[CNRS_topo_main_groups==type] ,
                     one_way) %>%
    bind_rows() %>%
    mutate(CNRS_topo_main_groups= type) %>%
    data.table()
  
  return(res_type)
}
    

do_table_5_new <- function(data = build_dyn_new(con = con),
                           one_way = F){
  
  data_probs_new<- data %>%  
    inner_join(new_test_cnr %>%select(id_var,DMG_age_quintiles),
               by = "id_var") %>% 
    data.table()
  
  uni_Age_Q = as.character(unique(data_probs_new$DMG_age_quintiles))
  uni_Age_Q = data.table::copy(uni_Age_Q[c(5,1,3,2,4)])
  uni_type_Q = as.character(unique(data_probs_new$CNRS_topo_main_groups))
  
  
  res_Age_new_t2 <- lapply(uni_Age_Q, table_2_age_new,data_probs_new,one_way=one_way ) %>%
    bind_rows() %>% 
    rename("DMG_age_quintiles" = "Category")
  
  
  res_Age_type <- lapply(uni_type_Q, do_all_age_groups,
                            data_probs_new,
                            one_way=one_way,
                             age_groups = uni_Age_Q) %>%
    bind_rows() %>% 
    rename("DMG_age_quintiles" = "Category")
  
  
  table_2_ageQ_all<-  rbind( res_Age_new_t2[, CNRS_topo_main_groups := " " ], 
                             res_Age_type)
  
  table_2_ageQ_all<- table_2_ageQ_all[order(CNRS_topo_main_groups)]
  
  setcolorder(table_2_ageQ_all,c("CNRS_topo_main_groups","DMG_age_quintiles"))
  
  
  table_2_ageQ_all[, c(3,4,5,6) := 
                     lapply(.SD, function(x){scales::comma(  x ,1) }), 
                   .SDcols = c(3,4,5,6)]
  
  return(table_2_ageQ_all)
}



do_table_5_month <- function(data = build_dyn_new(con = con),
                             name = "by_month",
                             one_way = F) {
  
  table_2_ageQ_all<- do_table_5_new(data, one_way = one_way)
  
  write.csv(table_2_ageQ_all[!is.na(Survivor_reweigthed)],paste0("Avg_Spending_Canc_by_Age_Quintile",name,".csv") )
  
  
  type_to_save<- c( " ", "Breast" ,  "Prostate gland",    "Colon",    "Bronchus and lung" ,    "Skin"  ,  "Bladder" ,
                    "Hemato. and reticul. systems"   ,     "Lymph nodes (secondary?)"   ,   "Stomach"  )                        
  
  labels_to_save<- c( " ", "Breast" ,  "Prostate",    "Colon",    "Bronchus and Lung" ,    "Skin"  ,  "Bladder" ,
                      "Hematopoietic System"   ,     "Lymph Nodes"   ,   "Stomach"  )                        
  
  levels_to_save<- c( " ", "Breast" ,  "Prostate gland",    "Colon",    "Bronchus and lung" ,    "Skin"  ,  "Bladder" ,
                      "Hemato. and reticul. systems"   ,     "Lymph nodes (secondary?)"   ,   "Stomach"  )                        
  
  
  table_2_ageQ_all<-table_2_ageQ_all[CNRS_topo_main_groups%in%type_to_save][,
                                                                            CNRS_topo_main_groups:=factor(CNRS_topo_main_groups,
                                                                                                          labels = labels_to_save,
                                                                                                          levels = levels_to_save)][
                                                                                                            order(CNRS_topo_main_groups)]
  
  
  table_2_ageQ_all<- table_2_ageQ_all[CNRS_topo_main_groups%in%type_to_save[1] | 
                                        (CNRS_topo_main_groups %in% labels_to_save[c(3,6,7)] & DMG_age_quintiles %in% c("(53,63]","(78,100]") )|
                                        (CNRS_topo_main_groups %in% labels_to_save[c(2,4:5,8:10)] & DMG_age_quintiles %in% c("[25,53]","(78,100]") ) ] 
  
  
  table_2_ageQ_all[CNRS_topo_main_groups %in% labels_to_save[c(3,6,7)]& DMG_age_quintiles == "(53,63]",
                   DMG_age_quintiles:=paste0(DMG_age_quintiles,"*")]
  
  setnames(table_2_ageQ_all,
           c("CNRS_topo_main_groups" ,"DMG_age_quintiles" ,  "Survivor_reweigthed"),
           c("" ,"Age Quintile","Survivor (Reweigted)"))
  
  library(knitr)
  library(kableExtra)
  options(knitr.kable.NA = '.')
  
  names(table_2_ageQ_all) <- c("","(1)", "(2)", "(3)", "(4)","(5)")
  
  table_2_ageQ_all %>% 
    kable("latex", booktabs = T, align = c("l","l", rep("r", ncol(.)-2))) %>%
    kable_styling(full_width = F ) %>%
    add_header_above(c("",
                       "Age Quintile",
                       "Unweighted",
                       "Reweighted by\nDecedent Risk", 
                       "",
                       "Decedent -\nSurvivor\n(Reweighted)"),underline = F,line = F) %>%
    add_header_above(c(" " = 2 , "Survivor" = 2, "Decedent" = 1 ,"Difference" =1  ), bold = T) %>%
    collapse_rows(1, latex_hline = "none", valign = "top") %>%
    pack_rows("A. All Cancer Types", 1, 5,latex_gap_space = "2em") %>%
    pack_rows("B. By Cancer Type", 6,23,latex_gap_space = "2em")  %>%
    row_spec(0, align = "c") %>% 
    write(paste0("Avg_Spending_Canc_by_Age_Quintile",name,".tex"))
  
  return(table_2_ageQ_all)
}

